package com.rankeiot.platform.service;

import cn.hutool.http.HttpUtil;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.exception.BusinessException;
import com.rankeiot.core.util.JSONUtil;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.platform.config.WxMpConfig;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序服务
 */
@Component
@Slf4j
public class WxMpService {
    final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    final String POST_USER_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
    final String GET_CODE_TO_SESSION_URL ="https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    /**
     * 获取微信小程序AccessToken
     *
     * @return
     */
    @Cacheable(key = "wx_mp_access_token")
    public String getAccessToken() {
        String appid = WxMpConfig.APP_ID.strValue();
        String secret = WxMpConfig.APP_SECRET.strValue();
        if (StringUtil.isEmpty(appid) || StringUtil.isEmpty(secret)) {
            Resp.fail("微信小程序配置错误");
        }
        String url=String.format(GET_ACCESS_TOKEN_URL,appid,secret);
        String resp = HttpUtil.get(url);

        System.out.println("获取AccessToken:" + resp);
        ONode node = ONode.load(resp);
        String accessToken = node.select("$.access_token").getString();
        if (accessToken == null) {
            Resp.fail("获取access_token失败");
        }
        return accessToken;
    }

    /**
     * 通过微信小程序code获取手机号
     *
     * @param code
     * @return
     */
    public String getPhoneNum(String code) {
        String accessToken = getAccessToken();
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        String url=String.format(POST_USER_PHONE_URL,accessToken);
        String respStr = HttpUtil.post(url, ONode.stringify(params));
        System.out.println("获取phoneNumber:" + respStr);
        ONode node = ONode.load(respStr);
        String phoneNumber = node.select("$.phone_info.phoneNumber").getString();
        if (phoneNumber == null) {
            Resp.fail("获取phoneNumber失败");
        }
        return phoneNumber;
    }

    /**
     * 通过微信小程序Code获取用户信息
     *
     * @param code
     * @return
     */
    public Map<String,String> userInfo(String code) {
        String accessTokenUrl = String.format(GET_CODE_TO_SESSION_URL,WxMpConfig.APP_ID.strValue(),WxMpConfig.APP_SECRET.strValue(),code); //"https://api.weixin.qq.com/sns/jscode2session?&appid=" + WxMpConfig.APP_ID.strValue() + "&secret=" + WxMpConfig.APP_SECRET.strValue() + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String result =  restTemplate.getForObject(accessTokenUrl, String.class, new Object[0]);
        if (StringUtil.isNotEmpty(result) && result.contains("errcode")) {
            ONode node = ONode.load(result);
            log.info("获取微信小程序accessToken失败，响应内容为: " + node.select("$.errmsg").getString());
            throw new BusinessException("微信小程序登录失败");
        } else {
            log.info("获取微信小程序accessToken成功，响应内容为: " + result);
            return JSONUtil.parseObject(result);
        }
    }
}
